<template>
  <div>
    <avue-form ref="form"
               class="add-body"
               v-model="obj"
               :option="options"
               @submit="submit">
      <template slot-scope="scope" slot="qzh">
        <el-select v-model="obj[scope.column.prop]" @change="handleQzh">
          <el-option v-for="(item, index) in scope.column.dicData"
                     :key="index"
                     :value="item.fondsNo"
                     :label="item.fondsNo + ' ' + item.fondsName"></el-option>
        </el-select>
      </template>
    </avue-form>
    <div class="btn-box">
      <el-button @click="handleSubmit"
                 type="primary"
                 :loading="loading"
                 size="small">
        确定
      </el-button>
      <el-button @click="handleSaveSubmit"
                 type="primary"
                 :loading="loading"
                 size="small">
        存加
      </el-button>
      <el-button style="margin-left: 10px" size="small" @click="handleEmpty">重置</el-button>
    </div>

  </div>
</template>

<script>
import {
  addElectronicsFile, addSaveData, addVolumerequest,
  editElectronicsFile
} from '../../../../../../api/electronicsFile/electronicsFile'
import { mapActions } from 'vuex'
import { getDepartmentList } from '../../../../../../api/department/department'
import { mapFields } from 'vuex-map-fields'
import { getClassificationTreeForm } from '../../../../../../api/classification'

export default {
  name: 'addVolume',
  components: { },
  // 新增案卷
  props: {
    fmtJson: {
      type: Array,
      default: () => ([])
    },
    type: {
      type: String,
      default: 'add'
    },
    idTable: {
      type: String
    },
    idCategory: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    formOptions: {
      // 表单
      type: Object,
      default: () => ({})
    },
    id: {
      type: String
    }
  },
  data () {
    return {
      saveType: 'save',
      bumenList: [], // 部门下拉框数据
      autosize: {
        minRows: 4,
        maxRows: 8
      },
      loading: false,
      obj: {},
      flhTree: []
    }
  },
  mounted () {
    if (this.type === 'edit') {
      this.obj = this.rowData
    } else {
      this.saveAddRequest(this.rowData.id)
    }
  },
  watch: {
    rowData: {
      handler (val) {
        if (this.type === 'add') {
          /* this.bumenList = []
          this.$refs.form.resetForm()
          this.obj.qzh = this.userInfo.fonsNo
          this.obj.zldw = this.userInfo.idOrg
          this.getBumen() */
          this.saveAddRequest(this.rowData.id)
        } else {
          this.obj = val
          this.getBumen()
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapFields('profile/profile', {
      userInfo: 'retrieved'
    }),
    options () {
      const form = {}
      Object.keys(this.formOptions).forEach(key => {
        if (key !== 'column') {
          form[key] = this.formOptions[key]
        } else {
          form.column = []
          this.formOptions.column.map((item, index) => {
            form.column.push(item)
            this.fmtJson.map((dhgz) => {
              if (dhgz.column === item.prop) {
                form.column[index].rules = [{
                  required: true,
                  message: '请输入' + dhgz.name,
                  trigger: 'blur'
                }]
              }
            })
            if (item.prop === 'zldw') {
              form.column[index].dicData = this.bumenList
            }
            if (item.prop === 'ajdh') {
              form.column[index].disabled = true
            }
            if (item.prop === 'flh') {
              form.column[index].dicData = this.flhTree
              form.column[index].type = 'tree'
              form.column[index].props = {
                label: 'categoryName',
                value: 'classificationCode',
                children: 'children'
              }
            }
          })
        }
      })
      form.column.map(item => {
        if (item.prop === 'ajdh') {
          const dhguize = []
          this.fmtJson.slice(0, this.fmtJson.length - 1).map((dhgz, index) => {
            if (this.obj[dhgz.column]) {
              if (dhgz.column === 'zldw') {
                this.bumenList.map(item => {
                  if (item.id === this.obj[dhgz.column]) {
                    dhguize[index] = item.orgCode
                  }
                })
              } else {
                dhguize[index] = this.obj[dhgz.column]
              }
              if (dhgz.length > this.obj[dhgz.column].length) {
                dhguize[index] = '0000000000'.substr(0, dhgz.length - this.obj[dhgz.column].length) + this.obj[dhgz.column]
              }
              dhguize[index] = dhguize[index] + dhgz.separator
            }
          })
          if (this.type === 'add') {
            this.obj.ajdh = dhguize.join('')
            this.obj.ajdh = this.obj.ajdh.replace(/-$/gi, '')
          }
        }
      })
      return form
    }
  },
  methods: {
    ...mapActions('electronicsFile/getHead', ['getTableList']),
    handleSubmit () {
      // 保存
      this.saveType = 'save'
      this.$refs.form.submit()
    },
    handleSaveSubmit () {
      // 存加
      this.saveType = 'saveAdd'
      this.$refs.form.submit()
    },
    saveAddRequest (idRec) {
      this.obj.qzh = this.userInfo.fonsNo
      this.getBumen()
      const idRecObj = idRec ? { idRec: idRec } : {}
      addSaveData(this.idTable, idRecObj).then(res => {
        Object.keys(this.obj).forEach(key => {
          if (key === 'zldw') {
            this.obj.zldw = this.userInfo.idOrg
          } else if (key === 'qzh') {
            this.obj.qzh = this.userInfo.fonsNo
          } else {
            this.obj[key] = ''
            if (res.data.data && res.data.data[key] !== 'null') {
              this.obj[key] = res.data.data[key]
            }
          }
        })
      })
    },
    handleQzh () {
      this.obj.zldw = ''
      this.getBumen()
    },
    getBumen () {
      // 根据全宗查部门
      const query = {
        pageSize: 1000,
        pageNo: 1,
        params: [{
          name: 'fondsNo',
          op: 'eq',
          value: this.obj.qzh
        }]
      }
      getDepartmentList(query).then(res => {
        this.bumenList = res.data.data.list
      })

      // 根据全宗和门类查分类号
      let qzId = ''
      this.options.column.map(item => {
        if (item.prop === 'qzh') {
          item.dicData.map(qz => {
            if (qz.fondsNo === this.obj.qzh) {
              qzId = qz.id
            }
          })
        }
      })
      const flhQuery = {
        idCategory: this.idCategory,
        fondsNoId: qzId
      }
      getClassificationTreeForm(flhQuery).then(res => {
        this.flhTree = res.data.data
      })
    },
    submit (form, done) {
      // 保存提交
      this.loading = true
      let requestFun = null
      if (this.type === '新增组卷') {
        requestFun = addVolumerequest(this.idTable, {
          data: form,
          ids: [this.id]
        })
      } else {
        if (this.type === 'add') {
          form.gdbs = 0
        }
        requestFun = this.type === 'add' ? addElectronicsFile({
          idTable: this.idTable,
          addType: 1,
          data: form
        }) : editElectronicsFile(this.idTable, {
          arcId: this.obj.id,
          data: form
        })
      }

      requestFun.then((res) => {
        if (this.volumeType === '新增组卷') {
          this.$message.success('新增组卷成功！')
        } else {
          this.$message.success(this.type === 'add' ? '新增成功！' : '修改成功！')
        }

        if (this.saveType === 'saveAdd') {
          this.saveAddRequest(res.data.data)
        }

        this.loading = false
        this.handleEmpty()
        if (this.saveType !== 'saveAdd') { this.$emit('handleSuccess') }
        done()
      }).catch(() => {
        this.loading = false
        done()
      })
    },

    handleEmpty () {
      // 清空内容
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
  .btn-box {
    text-align: right;
  }

  .add-body {
    height: calc(100vh - 170px);
    overflow-y: auto;
  }
</style>
